#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"

// GPIO9控制LED
#define LED_TASK_GPIO 9
#define LED_INTERVAL_TIME 30
#define LED_TASK_STACK_SIZE 512
#define LED_TASK_PRIO 25

enum LedState
{
    LED_ON = 0,
    LED_OFF,
    LED_SPARK,
};

enum LedState g_ledState = LED_ON;

static void *LedTask(const char *arg)
{
    (void)arg;
    switch (g_ledState)
    {
    case LED_ON:
        // 控制灯开
        IoTGpioSetOutputVal(LED_TASK_GPIO, 0);        
        break;
    case LED_OFF:
        // 控制灯关
        IoTGpioSetOutputVal(LED_TASK_GPIO, 1);
        osDelay(LED_INTERVAL_TIME);
        break;
    case LED_SPARK:
        // 控制灯闪
        IoTGpioSetOutputVal(LED_TASK_GPIO, 0);
        osDelay(LED_INTERVAL_TIME);
        IoTGpioSetOutputVal(LED_TASK_GPIO, 1);
        osDelay(LED_INTERVAL_TIME);
        break;    
    }
    return NULL;
}

static void LedExampleEntry(void)
{
    /*LED的GPIO初始化 */
    IoTGpioInit(LED_TASK_GPIO);
    /*GPIO设置为输出 */
    IoTGpioSetDir(LED_TASK_GPIO, IOT_GPIO_DIR_OUT);

    osThreadAttr_t attr;

    attr.name = "LedTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)LedTask, NULL, &attr) == NULL)
    {
        printf("[LedExample] Falied to create LedTask!\n");
    }
}

SYS_RUN(LedExampleEntry);
